import keras
import numpy as np
import pickle

# 加载模型
model = keras.models.load_model('./predict/model.h5')

with open('./predict/codec/supported_char_set.pickle.bin', 'rb') as f:
    supported_char_set = pickle.load(f)
with open('./predict/codec/supported_char_dict.pickle.bin', 'rb') as f:
    supported_char_dict = pickle.load(f)


def to_name_categorical(chinese_name: str):
    """
    中文姓名标签化
    :param chinese_name: 中文名字
    :return:
    """
    assert len(chinese_name) <= 5, '名字过长：' + chinese_name
    assert set(chinese_name).issubset(supported_char_set), "名字中含有不受支持的字符：%s" % chinese_name
    if len(chinese_name) < 5:
        chinese_name += ' ' * (5 - len(chinese_name))
    return np.array([supported_char_dict[name_char] for name_char in chinese_name])


def name_predict(name_to_predict: str):
    """
    预测姓名对应的性别
    :param name_to_predict: 中文姓名
    :return:
    """
    global model
    name_matrix = to_name_categorical(name_to_predict).reshape(-1, 5)
    predict_res = model.predict(name_matrix)[0][0]
    gender = '男' if predict_res > 0.5 else '女'
    accuracy = predict_res if predict_res > 0.5 else 1 - predict_res
    return {'name': name_to_predict, 'gender': gender, 'accuracy': str(accuracy),
            'text': "%s 为%s生，预测概率为：%f" % (name_to_predict, gender, accuracy)}
